package com.example.podapp;

import java.util.Hashtable;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import podapp.helper.AlertDialogManager;
import podapp.helper.ConnectionDetector;
import InternetServices.WebServiceCall;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	String JsonResponse = "";
	Button btnSubmit = null;
	EditText txtUserid = null;
	EditText txtPassword = null;
	String Userid = "";
	String Password = "";
	private ProgressDialog pDialog;
	ConnectionDetector cd;
	AlertDialogManager alert = new AlertDialogManager();
	Map<String, String> map = new Hashtable<String, String>();
    
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		cd = new ConnectionDetector(getApplicationContext());
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		txtUserid = (EditText) findViewById(R.id.txtUserId);
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		txtUserid.clearFocus();
		// check for Internet Connection
		if (!cd.isConnectingToInternet()) {
			AlertDialog.Builder dialog = new AlertDialog.Builder(
					MainActivity.this);
			dialog.setTitle("\tInternet Connection Error");
			dialog.setMessage("\tYou do not have internet access at this time. \n \t Please enable internet access.");
			dialog.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			dialog.show();
			return;
		}

		btnSubmit = (Button) findViewById(R.id.btnLogin);

		btnSubmit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (validateUser()) {
					AsyncWebServiceCall task = new AsyncWebServiceCall();
					task.execute();
				}
			}
		});
	}

	public boolean validateUser() {
		if (txtUserid.getText().toString().equalsIgnoreCase("")) {
			Toast t = Toast.makeText(getApplicationContext(),
					"Please Enter UserID.", Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER_HORIZONTAL, 10, 10);
			t.show();
			txtUserid.requestFocus();
			return false;
		}
		if (txtPassword.getText().toString().equalsIgnoreCase("")) {
			Toast t = Toast.makeText(getApplicationContext(),
					"Please Enter Password.", Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER_HORIZONTAL, 10, 10);
			t.show();
			txtPassword.requestFocus();
			return false;
		}
		return true;
	}

	public class AsyncWebServiceCall extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			map.put("UserID", txtUserid.getText().toString());
			map.put("Password", txtPassword.getText().toString());
			WebServiceCall webObj = new WebServiceCall();
			JsonResponse = webObj.webServiceMethod("ValidateForPodLogin", map);
			if (JsonResponse != "") {
				JSONObject jsonObj;
				try {
					jsonObj = new JSONObject(JsonResponse);
					JSONArray JsonArr = jsonObj.getJSONArray("Result");
					if (JsonArr.length() != 0) {
						for (int i = 0; i < JsonArr.length(); i++) {
							JSONObject jsonChild = JsonArr.getJSONObject(i);
							Userid = jsonChild.getString("UserID");
							Password = jsonChild.getString("UserPass");
						}
						Log.d("Name: ", Userid);
						Log.d("Password: ", Password);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			if (txtUserid.getText().toString()
					.equalsIgnoreCase((Userid.toString()))
					&& txtPassword.getText().toString()
							.equalsIgnoreCase((Password.toString()))) {
				Intent i = new Intent(MainActivity.this, CaseListActivity.class);
				i.putExtra("UserID", Userid);
				startActivity(i);
			} else {
				alert.showAlertDialog(MainActivity.this, "Login Error.",
						"Invalid Userid or Password.", false);
				txtPassword.setText("");
			}

		}
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
		dialog.setTitle("Message");
		dialog.setMessage("Do you want to exit PODApp ?.");
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		dialog.setNegativeButton("Cancel", null);
		dialog.show();
		return;
	}

}
